<?php
    /**
     * @name mysql数据库类
     * @copyright tcsos inc
     * @version cooperation v1.0
     */
    class mysql{
        private $db_host; //数据库主机
        private $db_user; //数据库用户名
        private $db_pwd; //数据库用户名密码
        private $db_database; //数据库名
        private $db_port; //端口
        private $conn; //数据库连接标识;
        private $coding; //数据库编码，GBK,UTF8,gb2312
        private $log;   //日志对象        
        private $result_ary = array();              //Query处理后的结果集        

        /**
         * 构造函数
         * 
         * @param array $db_config  配置文件
         * @return void
         */
        public function __construct($db_config, $log){
            if(empty($log) || empty($db_config) || empty($db_config['host']) || empty($db_config['usr']) || empty($db_config['pwd']) || empty($db_config['database'])) {
                exit('class mysql __construct exit.');
            }
            $this->log = $log;            
            $this->db_host = $db_config['host'];
            $this->db_user = $db_config['usr'];
            $this->db_pwd = $db_config['pwd'];
            $this->db_database = $db_config['database'];
            $this->db_port = $db_config['port'] > 0 ? $db_config['port'] : 3306;
            $this->coding = $db_config['charset'] != '' ? $db_config['charset'] : 'utf8';            
            $this->connect();            
        }

        /**
         * 析构函数
         * 
         * @return void
         */
        public function __destruct(){                     

            //清除所有的result
            foreach($this->result_ary as $v) {
                if(!is_resource($v)) {
                    continue;
                }                
                mysql_free_result($v);
            }                        

            if(!$this->conn || !is_resource($this->conn)){
                return false;
            }
            mysql_close($this->conn); 
        }        

        /**
         * 数据库连接
         * 
         * @return 成功返回true，失败则退出
         */
        private function connect() {
            $this->conn = mysql_connect($this->db_host.':'.$this->db_port, $this->db_user, $this->db_pwd);
            if(!$this->conn){
                exit('class mysql _connect error !');
            }
            $this->select_db();
            return true;
        }

        /**
         * 选择数据库
         * 
         * @param string $db_database   数据库名
         * @return 成功返回true，失败退出
         */
        public function select_db($db_database = ''){
            if($db_database == ''){
                $db_database = $this->db_database;
            }
            if(!mysql_select_db($db_database, $this->conn)) {
                exit('class mysql _select_db error !');
            }
            $this->query('SET NAMES '.$this->coding);            
            return true;
        }        

        /**
         * 返回多行结果集
         * 
         * @param string $sql    SQL语句
         * @return array    成功返回结果集，失败返回false 
         */
        public function find($sql){
            $rowset = false;
            if($sql == ''){
                return $rowset;
            }
            $this->sql = $sql;
            $result = $this->query($this->sql, true);

            if(!$result){
                return $rowset;
            }

            while($row = mysql_fetch_array($result , MYSQL_ASSOC)){
                $rowset[] = $row;
            }                        

            return $rowset;
        }        

        /**
         * 返回单行结果集
         * 
         * @param string $sql   SQL语句
         * @return array    成功返回结果集，失败返回false 
         */
        public function findone($sql){
            $rowset = false;
            if($sql == ''){
                return $rowset;
            }
            $this->sql = $sql;
            $result = $this->query($this->sql, true);

            if(!$result){
                return $rowset;
            }

            if($row = mysql_fetch_array($result , MYSQL_ASSOC)){
                $rowset = $row;
            }       

            return $rowset;
        }

        /**
         * 进行插入操作，并返回插入ID
         * 
         * @param string $sql   SQL语句
         * @return bool
         */
        public function insert($sql) {
            if(empty($sql)) {
                return false;
            }
            $this->query($sql);
            return mysql_insert_id($this->conn);
        }

        /**
        * 进行更新操作，返回影响的行数，没有改变的行不计数
        * @author zhufu 2014-04-09
        * 
        * @param string $sql 更新语句
        * @return mixed 成功返回成功的记录数，失败返回 false
        */
        public function update($sql){
            if(!$sql){
                return false;
            }
            $this->query($sql);
            return mysql_affected_rows();
        }
        
        /**
         * 直接执行一条SQL语句
         *                  
         * @param string $sql   SQL语句
         * @param bool  $rtn    是否返回值
         * @return $rtn为true返回MYSQL资源号
         */
        public function query($sql, $rtn = false) {
            $t1 = microtime();
            $t1 = explode(' ', $t1);
            $t1 = array_sum($t1);
                        
            $result = @mysql_query($sql, $this->conn);
            
            $t2 = microtime();
            $t2 = explode(' ', $t2);
            $t2 = array_sum($t2);
            
            if($t2 - $t1 > 1){
                $log_level = 1; 
                $this->log->write_log('SQL:' . $sql , $log_level);
            }
            
            $log_level = 2;
            //如果执行SQL错误，查看SQL等级
            if(!$result) {
                $log_level = 1;   
            }

            $sql = strtolower($sql);

            //写入日志
            if(strexists($sql, 'insert') || strexists($sql, 'delete') || strexists($sql, 'update')) {
                $this->log->write_log('SQL:' . $sql , $log_level);
            }

            //存入result集合中
            array_push($this->result_ary, &$result);            

            if($rtn) {
                return $result;
            }
        }                

        /**
         * 分页查询
         *         
         * @param string $sql       SQL语句
         * @param int $curpage         当前页
         * @param int $pagesize     每页显示数
         */
        public function findlimit($sql, $curpage = 1, $pagesize = 10, $count=false) {            
            if($curpage < 1 || $pagesize < 1) {
                return false;
            }                                

            //统计查询
            if($count === false){
                $count = 0;
                $count_sql = preg_replace("/select\s+(.*?)\s+from/i", 'select count(*) as count from', $sql);
                $count_sql = preg_replace('/\border\b.*/i', '', $count_sql);
                $count = $this->findone($count_sql); 
                $count = $count['count'];  
            }
                    
            
            
            /*        
            $result = $this->query($sql, true);
            if($result) {
                $count = mysql_num_rows($result);                                
            } 
            */           

            //分页查询
            $sql .= ' limit ' . (($curpage - 1) * $pagesize) . ',' . $pagesize;
            $datarows = $this->find($sql);

            $pagetotal = $count % $pagesize;
            if($pagetotal < 1) {
                $pagetotal = $count/$pagesize;
            } else {
                $pagetotal = ceil($count/$pagesize);
            }

            if($curpage > $pagetotal){
                $curpage = $pagetotal;
            }                         

            return array(
            'row_count' => $count ,         //总数据
            'page_count' => $pagetotal ,    //总页数
            'cur_page' => $curpage ,        //当前页                
            'page_size'=>  $pagesize,       //每页显示数
            'rows' => $datarows             //数据集
            );
        }

        /**
         * 将表字段缓存
         * 
         * @author zhouqi 2012-5-4 PM 14:49:02
         * @param string $table 表名
         */
        public function flush($table) {
            if(!$table) {
                return false;
            }

            $result = $this->fields($table);
            if(!$result) {
                return false;
            }

            $fields = array_keys($result);
            $fields['_autoinc'] = false;
            foreach ($result as $k => $v){
                // 记录字段类型
                $type[$k] = $v['type'];

                if(!$v['primary']) {
                    continue;
                }

                //获取关键字
                $fields['_pk'] = $k;

                //自动
                if(!$v['autoinc']) {
                    continue;
                }

                $fields['_autoinc'] = true;                
            }

            $fields['_type'] = $type;

            //缓存字段
            F("_fields/{$table}", $fields);
            return $fields;
        }

        /**
         * 获取字段信息
         * 
         * @author zhouqi 2012-5-4 PM 13:46:07
         * @param string $table   表名
         */
        private function fields($table) {
            $rowset = false;
            if($table === '') {
                return $rowset;
            }

            $this->sql = "SHOW COLUMNS FROM {$table}";
            $result = $this->find($this->sql);

            if(!$result) {
                return false;
            }

            $data = array();
            foreach($result as $k => $v) {
                $data[$v['Field']] = array(
                'name'    => $v['Field'],
                'type'    => $v['Type'],
                'notnull' => (bool) ($v['Null'] === ''),
                'default' => $v['Default'],
                'primary' => (strtolower($v['Key']) == 'pri'),
                'autoinc' => (strtolower($v['Extra']) == 'auto_increment'),
                );
            }
            return $data;
        }
    }
?>
